package se.vgregion.excel.tools;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;

/**
 * Functionality to write the user name within a excel document.
 * 
 * @author claes.lundahl
 * 
 */
public class ExcelDocReplacer extends ZipToZipWriter {

    private String currentUserName;
    private String newUserName;

    /**
     * Starts the process.
     * 
     * @param in
     *            document passed into the method.
     * @param os
     *            document after it has been modified.
     * @param currentUserName
     *            the user-name currently coded into the document (from the in parameter).
     * @param newUserName
     *            new name or id to use in the file.
     */
    public void process(InputStream in, OutputStream os, String currentUserName, String newUserName) {
        this.currentUserName = currentUserName;
        this.newUserName = newUserName;
        super.process(in, os);
    }

    @Override
    protected void visit(ZipEntry entry, int bytesIn, byte[] readBuffer) {

        if (currentUserName == null || newUserName == null) {
            String sn = getClass().getSimpleName();
            throw new RuntimeException("Dont use the " + sn + ".process(InputStream in), use the " + sn
                    + ".process(InputStream in, OutputStream os, String currentUserName, String newUserName) "
                    + "with non-null values for all parameters.");
        }

        if (entry.getName().endsWith(".xml")) {
            String s = new String(Arrays.copyOf(readBuffer, bytesIn));
            if (s.contains(currentUserName)) {
                s = s.replaceAll(Pattern.quote(currentUserName), newUserName);
                byte[] newBytes = s.getBytes();
                bytesIn = newBytes.length;
                for (int i = 0; i < bytesIn; i++) {
                    readBuffer[i] = newBytes[i];
                }
            }
        }

        super.visit(entry, bytesIn, readBuffer);
    }

}
